/**
 *  Copyright (C) 2010  Thomas Volk
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package com.googlecode.bookmarks.core.beans;

import java.net.MalformedURLException;
import java.net.URL;

import javax.persistence.Column;
import javax.persistence.Entity;

@Entity
abstract public class RemoteResource extends Resource {
	@Column(length = 1024, nullable = false)
	private String host;
	private Integer port;

	public RemoteResource() {
	}

	public RemoteResource(URL url) {
		super(url.getPath());
		update(url);
	}

	private void update(URL url) {
		host = url.getHost();
		int urlPort = url.getPort();
		if (urlPort >= 0) {
			port = urlPort;
		}
	}

	public URL getUrl() {
		if (getLocation() == null || getHost() == null || getProtocol() == null) {
			return null;
		} else {
			int urlPort = port == null ? -1 : port;
			try {
				return new URL(getProtocol(), getHost(), urlPort, getLocation());
			} catch (MalformedURLException e) {
				throw new RuntimeException(e);
			}
		}
	}

	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public void setUrl(URL url) {
		setLocation(url.getPath());
		update(url);
	}

}
